/*
 * Copyright 2020-2030 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gitee.minimalismstyle.fresh.gateway.config

import com.gitee.minimalismstyle.fresh.common.core.extra.log
import com.gitee.minimalismstyle.fresh.gateway.route.MyRouteDefinition
import org.springframework.cloud.gateway.route.RouteDefinitionRepository
import org.springframework.context.annotation.Primary
import org.springframework.stereotype.Component
import springfox.documentation.swagger.web.SwaggerResource
import springfox.documentation.swagger.web.SwaggerResourcesProvider
import java.util.*

/**
 * Swagger接口文档采集配置
 * @author maoxiaodong
 */
@Component
@Primary
class SwaggerResourceConfig(var routeDefinitionRepository: RouteDefinitionRepository) : SwaggerResourcesProvider {

    override fun get(): List<SwaggerResource> {
        val resources: MutableList<SwaggerResource> = mutableListOf()
        val routes: MutableList<MyRouteDefinition> = ArrayList()
        routeDefinitionRepository.routeDefinitions.subscribe { routes.add(it as MyRouteDefinition) }

        routes.stream().forEach { route ->
            route.predicates.stream()
                    .filter { "Path".equals(it.name, ignoreCase = false) }
                    .forEach {
                        resources.add(swaggerResource(route.routeName!!,
                                it.args["pattern"]!!
                                        .replace("**", "v2/api-docs")))
                    }
        }
        return resources
    }

    private fun swaggerResource(name: String, location: String): SwaggerResource {
        log.info("name:{},location:{}", name, location)
        val swaggerResource = SwaggerResource()
        swaggerResource.name = name
        swaggerResource.location = location
        swaggerResource.swaggerVersion = "2.0"
        return swaggerResource
    }
}